package org.duang.handles;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.duang.kit.ToolsKit;

/**
 * 添加允许跨域访问的域名 Map<String,String> key为代号,value为域名
 * 
 * @author laotang
 * @since 1.0
 */
public class AllowHostHandle implements IHandle {

	private String allowHostKey;
	private Map<String, String> accessHosts;
	private final static String PROTOCOL = "http://";
	private final static String PROTOCOLS = "https://";
	private final static String PROTOCOLS_EXT_NAME = "_https";
	private final static String FORWARDED_PROTO = "X-Forwarded-Proto";
	private final static String FORWARDED_FOR = "X-Forwarded-For";
	

	/**
	 * 允许跨域访问的域名集合
	 * 
	 * @param accessHosts
	 */
	public AllowHostHandle(String allowHostKey, Map<String, String> accessHostMap) {
		if (ToolsKit.isNotEmpty(allowHostKey) && ToolsKit.isNotEmpty(accessHostMap)) {
			this.allowHostKey = allowHostKey;
			this.accessHosts = new HashMap<String, String>(accessHostMap.size());
			for (Iterator<Entry<String, String>> it = accessHostMap.entrySet().iterator(); it.hasNext();) {
				Entry<String, String> entry = it.next();
				String host = entry.getValue().toLowerCase();
				if (host.startsWith(PROTOCOL) || host.startsWith(PROTOCOLS)) {
					throw new IllegalArgumentException("please don't set protocol...");
				}
				this.accessHosts.put(entry.getKey(), host);
			}
		}
	}

	@Override
	public void execute(String target, HttpServletRequest request, HttpServletResponse response) throws Exception {

		  String host = "";
	        String allowhost =  request.getHeader("Origin"); //httpRequest.getRequestURL().toString();
	        if(ToolsKit.isEmpty(allowhost)) {
	        	allowhost = request.getHeader("Referer");
	        	if(ToolsKit.isEmpty(allowhost)) {
	        		allowhost = request.getHeader("Host");
	        	}
	        	if(ToolsKit.isNotEmpty(allowhost)) {
		        	int indexOf = allowhost.indexOf("com") ;
		        	if(ToolsKit.isEmpty(allowhost) && (indexOf > -1)) {
		        		allowhost = allowhost.substring(0, indexOf+3);
		        	}
	        	}
	        } 
	        if(ToolsKit.isNotEmpty(allowhost)){
	        		host = allowhost;
	        		allowhost = allowhost.replace("http://","").replace("https://","");
	        	   if(!accessHosts.containsValue(allowhost)) {
	        		   host = "";
	               }
	        } else {
	        	String key = request.getParameter("allowhost");
	        	host = getScheme(request) + "://" + accessHosts.get(key);
	        }
	        
	        if(ToolsKit.isNotEmpty(host)) {
	        	response.setHeader("Access-Control-Allow-Origin", host.endsWith("/") ? host.substring(0, host.length()-1) : host);
	        	response.setHeader("Access-Control-Allow-Credentials", "true");
	        	response.setHeader("Access-Control-Allow-Headers", "accept, content-type");
	        }
	}

	private String getScheme(HttpServletRequest httpRequest ) {
		String forwardedProto = httpRequest.getHeader(FORWARDED_FOR);
		forwardedProto = ToolsKit.isEmpty(forwardedProto) ? httpRequest.getHeader(FORWARDED_PROTO) : forwardedProto;
		if (ToolsKit.isEmpty(forwardedProto)) {
			forwardedProto = httpRequest.getScheme();
		}
		return forwardedProto;
	}

}
